import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

const createProxy = (baseApi, targetUrl) => ({
  target: targetUrl,
  changeOrigin: true,
  rewrite: (path) => path.replace(new RegExp(`^/${baseApi}`), '/xddcloud'),
});

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_PORT, VITE_APP_API_URL } = env;
  const port = Number(VITE_APP_PORT) || 3000;

  const proxyConfig = {
    '/xddcloud': createProxy('xddcloud', VITE_APP_API_URL),
  };

  const buildConfig = {
    outDir: 'dist',
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,     // 删除 console 语句
        drop_debugger: true,    // 删除 debugger 语句
        keep_infinity: true,    // 保留 Infinity 变量
      },
      format: {
        comments: false,        // 删除注释
      },
    },
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html'),
      },
      output: {
        entryFileNames: 'assets/js/[name]-[hash].js',
        chunkFileNames: 'assets/js/chunk-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
      },
    },
    cssCodeSplit: true,
    emptyOutDir: true,           // 清空输出目录
  };

  const resolveConfig = {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@assets': path.resolve(__dirname, 'src/assets'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@views': path.resolve(__dirname, 'src/views'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@directives': path.resolve(__dirname, 'src/directives'),
      '@constants': path.resolve(__dirname, 'src/constants'),
      '@node_modules': path.resolve(__dirname, 'node_modules'),
    },
    extensions: ['.js', '.vue', '.ts', '.jsx'],
  };

  const cssConfig = {
    preprocessorOptions: {
      scss: {
        additionalData: '@import "@/assets/styles/variables.scss";',
        charset: false,
      },
    },
  };

  return {
    base: '/',
    plugins: [vue()],
    server: {
      host: '0.0.0.0',
      port,
      open: false,
      strictPort: false,
      https: false,
      proxy: proxyConfig,
    },
    build: buildConfig,
    resolve: resolveConfig,
    css: cssConfig,
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: process.env.NODE_ENV === 'production' ? 'true' : 'false',
    },
  };
});
